<script setup lang="ts">
import router from '@/router'
import axios from '@/http/axios'
import { toDisplayString, watch } from 'vue'
import { onMounted } from 'vue'
import { reactive, ref } from 'vue'
import { toRefs } from 'vue'
import { useRoute } from 'vue-router'
import { useLoginStore } from '@/stores/LoginStore'
import { ElNotification } from 'element-plus'
let total_flowers = ref(20)
let use = ['爱情鲜花', '生日鲜花', '友情鲜花', '探病问候', '道歉鲜花', '问候长辈', '感谢老师', '哀思鲜花', '商务鲜花']
let flower = ['玫瑰', '百合', '康乃馨', '向日葵', '满天星', '郁金香', '菊花', '其他']
let type = ['花束', '礼盒', '蛋糕', '花篮', '绿植', '周花', '手提花篮', '桌花', '其他']
let branch = ['11枝', '19枝', '21枝', '33枝', '52枝', '66枝', '99枝', '其他']
let flowerId = reactive<number[]>([])
let userId = ref()
let imgsrc = reactive([''])
let name = reactive([''])
let price = reactive([''])
let material = reactive([''])
let category = reactive([''])
let dialogVisible = ref(false)
let num = ref(1)
let i = 0
let FlowerQueryDTO = reactive({
  name: null, 
  use: null,
  material: null,
  category: null,
  count: null,
  pageNum: null
})

const route = useRoute()
let { query } = toRefs(route)
console.log("name:"+query.value.keyword)
console.log("category:"+query.value.category)

if (query.value.keyword) {
  FlowerQueryDTO.name = query.value.keyword as any
}
if (query.value.category) {
  FlowerQueryDTO.category = query.value.category as any
}

const loginStore = useLoginStore();
console.log("username:" + loginStore.loginUsername)

watch(
  // 监听的目标：路由参数
  () => route.query,
  // 变化时的回调
  async (newParams, oldParams) => {
    console.log('参数变化:', newParams, oldParams)
    if (newParams.keyword) {
      FlowerQueryDTO.name = newParams.keyword as any
    }
    if (newParams.category) {
      FlowerQueryDTO.category = newParams.category as any
    }
    
    // 调用数据加载函数
     await loadFlowerData()
  },
  // 配置项：如果参数是对象，浅层监听即可（路由参数变化会生成新对象）
  { immediate: false } // 初始不执行，首次数据在onMounted中加载
)

async function loadFlowerData() {
  try {
    console.log("开始加载数据，查询参数:", FlowerQueryDTO)
    let res = await axios.get(`/flower`, {
      params: FlowerQueryDTO
    })
    let a = res.data
    let len = a.length
    // 清空原有数据
    imgsrc.length = 0
    name.length = 0
    price.length = 0
    material.length = 0
    category.length = 0
    flowerId.length = 0

    for (let i = 0; i < len; i++) {
      flowerId[i] = a[i].flowerId
      imgsrc[i] = a[i].image
      name[i] = a[i].name.slice(0, 8)
      price[i] = a[i].price
      material[i] = a[i].material
      category[i] = a[i].category
    }
    console.log("数据加载完成")
  } catch (error) {
    console.error("数据加载失败:", error)
  }
}



// 在组件挂载时调用数据加载函数
onMounted(async () => {
  console.log("组件开始挂载")
  
  // 处理初始路由参数
  if (query.value.keyword) {
    FlowerQueryDTO.name = query.value.keyword as any
  }
  if (query.value.category) {
    FlowerQueryDTO.category = query.value.category as any
  }
  
  // 调用数据加载函数
  await loadFlowerData()
  
  // 获取用户ID和购物车数据（这部分保持不变）
  const response = await axios.get(`/cart`, {
    headers: {
      'Authorization': loginStore.loginToken
    }
  });
  userId.value = response.data.userId;
  
  console.log("组件挂载完成")
});
console.log(imgsrc)

async function changeUse(use: string | null, i: number) {
  console.log(use)
  FlowerQueryDTO.name = null
  if (i == 1) {
    FlowerQueryDTO.use = use as null
  }
  if (i == 2) {
    FlowerQueryDTO.material = use as null
  }
  if (i == 3) {
    FlowerQueryDTO.category = use as null
  }
  if (i == 4) {
    FlowerQueryDTO.count = use as null
  }
  // 接收点击的值作为参数
  let res = await axios.get(`/flower`, {
    params: FlowerQueryDTO
  })
  let a = res.data
  let len = a.length
  // 清空原有数据
  imgsrc.length = 0
  name.length = 0
  price.length = 0

  for (let i = 0; i < len; i++) {
    imgsrc[i] = a[i].image
    name[i] = a[i].name.slice(0, 8)
    price[i] = a[i].price
    material[i] = a[i].material
    category[i] = a[i].category
  }
}
async function changeCurrent(currentPage: number) {
  console.log(currentPage)
  Object.assign(FlowerQueryDTO, { pageNum: currentPage })
  // 接收点击的值作为参数
  let res = await axios.get(`/flower`, {
    params: FlowerQueryDTO
  })
  let a = res.data
  let len = a.length
  // 清空原有数据
  imgsrc.length = 0
  name.length = 0
  price.length = 0

  for (let i = 0; i < len; i++) {
    imgsrc[i] = a[i].image
    name[i] = a[i].name.slice(0, 8)
    price[i] = a[i].price
  }
}
function onclick(index: number) {
  i = index
  dialogVisible.value = true
}

function handleChange(val: number) {
  num.value = val
}

async function addFlower(flowerId: number, userId: number, count: number) {
  console.log("userId:" + userId)
  if(loginStore.loginUsername == ""){
    ElNotification({
      title: 'Error',
      message: "请先登录",
      type: 'error',
      duration: 600,
    })
    dialogVisible.value = true
    router.push('/login')
  }else{
    dialogVisible.value = false
    const cart = await axios.get(`/cart/getcart/${userId}/${flowerId}`);
    console.log("cart.data:" + cart.data)
    let res = null
    if (Number(cart.data) != 0) {
      res = await axios.put(`/cart/updateCount/${userId}/${flowerId}/${count + cart.data}`);
      console.log(res.data.code)
    } else {
      res = await axios.post(`/cart/addFlower/${userId}/${flowerId}/${count}`);
      console.log(res.data.code)
    }
    console.log(res.data.code)
    if(res.data.code == 200){
      ElNotification({
        title: 'Success',
        message: "添加成功",
        type: 'success',
        duration: 600,
      })
    }else{
      ElNotification({
        title: 'Error',
        message: "添加失败",
        type: 'error',
        duration: 600,
      })
    }
  }
}
</script>

<template>
  <div class="sort-view">
    <div class="sort-view-top-title">
      <p>首页>{{ FlowerQueryDTO.use }}>{{ FlowerQueryDTO.material }}>{{ FlowerQueryDTO.category }}>{{ FlowerQueryDTO.count
      }}</p>
    </div>
    <div class="sort-view-top">
      <table cellpadding="8" cellspacing="0">
        <tr class="sort-view-top-tr">
          <th>用途</th>
          <td v-for="item in use"><a href="#" @click="changeUse(item, 1)">{{ item }}</a></td>
        </tr>
        <tr class="sort-view-top-tr">
          <th>花材</th>
          <td v-for="item in flower"><a href="#" @click="changeUse(item, 2)">{{ item }}</a></td>
        </tr>
        <tr class="sort-view-top-tr">
          <th>类别</th>
          <td v-for="item in type"><a href="#" @click="changeUse(item, 3)">{{ item }}</a></td>
        </tr>
        <tr class="sort-view-top-tr">
          <th>枝数</th>
          <td v-for="item in branch"><a href="#" @click="changeUse(item, 4)">{{ item }}</a></td>
        </tr>
      </table>
    </div>
    <div class="sort-view-center">
      <div v-for="(value, index) in imgsrc" class="sort-view-flower">
        <a href="#" style="cursor: pointer;"><img :src="value" alt="" @click="onclick(index)"></a>
        <p class="sort-view-flower-name">{{ name[index] }}</p>
        <p class="sort-view-flower-price">￥{{ price[index] }}</p>
      </div>
    </div>
    <div class="sort-view-pagination">
      <el-pagination background layout="prev, pager, next" :total="total_flowers" @current-change="changeCurrent" />
    </div>
  </div>

  <el-dialog v-model="dialogVisible">
    <div class="dialog-content">
      <img :src="imgsrc[i]" class="dialog-image">
      <div>
        <div style="font-size: 20px; font-weight: bold;">{{ name[i] }}</div>
        <hr>
        <div>种类：{{ material[i] }}</div>
        <div>类别：{{ category[i] }}</div>
        <div class="flower-info">
          <div>价格：</div>
          <div style="font-size: 18px; color:red">￥{{ price[i] }}</div>
        </div>
      </div>
    </div>
    <div>
      <el-input-number v-model="num" :min="1" @change="handleChange" class="input-number" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <!-- userid待获取，暂为死数据 -->
        <el-button type="primary" @click="addFlower(flowerId[i], userId, Number(num))">
          加入购物车
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped>
.sort-view {
  width: 100%;
  min-height: 100vh;
  background-color: #e1e1e1;
  overflow: hidden;
}

.sort-view-top-title {
  width: 85%;
  height: 35px;
  margin: 0 auto;
  line-height: 35px;
}

.sort-view-top {
  width: 85%;
  height: 230px;
  margin: 0 auto;
  background-color: #ffffff;
}

.sort-view-top table {
  width: 100%;
  border-collapse: collapse;
}

.sort-view-top-tr {
  height: 40px;
  line-height: 40px;
  border-bottom: 1px dashed #ff0000;
  padding: 8px;
}

.sort-view-top-tr td a {
  /* 去掉a标签的样式 */
  color: #000000;
  text-decoration: none;
  padding-left: 15px;
  padding-right: 15px;
}

.sort-view-top-tr td a:hover {
  color: #ffcc00;
}

.sort-view-center {
  width: 85%;
  margin: 20px auto;
  overflow: hidden;
  display: flow-root;
}

.sort-view-center div {
  width: 24%;
  height: 360px;
  float: left;
  margin-left: 6px;
  margin-right: 5px;
  margin-bottom: 12px;
  margin-top: 10px;
  background-color: #ffffff;
}

.sort-view-flower img {
  width: 300px;
  height: 300px;
  background-color: aqua;
  margin-left: 4px;
}

.sort-view-flower img:hover {
  transform: scale(1.05);
}

.sort-view-flower-name {
  font-size: 22px;
  font-weight: bolder;
  margin-left: 10px;
  margin-top: -5px;
}

.sort-view-flower-price {
  margin-left: 10px;
  margin-top: -20px;
  color: #ff0000;
}

.sort-view-pagination {
  width: 30%;
  height: 40px;
  margin: 0 auto;
  line-height: 40px;
}

.dialog-content {
  display: flex;
  width: 70%;
  margin: 0 auto;
}

.dialog-image {
  width: 200px;
  height: 200px;
  margin: 0 20px 20px 0;
}

.flower-info {
  display: flex;
  line-height: 30px;
}

.input-number {
  transition: fixed;
  left: 330px;
}
</style>